package com.sisyphus.spinach.network;

import com.sisyphus.spinach.core.INetPageTask;
import com.sisyphus.spinach.core.model.IPageResponse;
import com.sisyphus.spinach.core.model.IResponse;
import com.sisyphus.spinach.network.exceptions.ServeResponseException;

import androidx.annotation.NonNull;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class ResponsePageObserver<T, V extends INetPageTask.View<T>> implements Observer<IResponse<? extends IPageResponse<T>>> {

    private final int mPage;

    private final INetPageTask.View<T> mView;

    private final INetPageTask.Presenter<T, V> mPresenter;


    public ResponsePageObserver(
            int page,
            @NonNull INetPageTask.View<T> view,
            @NonNull INetPageTask.Presenter<T, V> presenter
    ) {

        mPage = page;
        mView = view;
        mPresenter = presenter;
    }


    @Override
    public void onSubscribe(Disposable d) {
        mPresenter.add(d);
    }

    @Override
    public void onNext(IResponse<? extends IPageResponse<T>> t) {
        // ? extends IResponse<? extends IPagination<T>>
        if (t == null) {
            onError(new NullPointerException("ResponseObserver onNext(T t) return object is null"));
            return;
        }

        if (!t.isSuccessful()) { // 失败
            onError(new ServeResponseException(t.getMessage(), t.getErrorCode(), t.getData()));
            return;
        }

        mView.complete();
        IPageResponse<T> pagination = t.getData();

        if (mPage <= 1) {
            mView.renderRefresh(pagination.getList());

        } else {
            mView.renderLoadMore(pagination.getList());
        }

        if (!pagination.hasMore()) {
            mView.renderNoMore();
        }
    }

    @Override
    public void onError(Throwable e) {
        mView.complete();
        mView.failure(e);
        e.printStackTrace();
    }

    @Override
    public void onComplete() {

    }

}
